package com.huangsm.book.designmodel.key;

/**
 * 理解Volatile关键字的小Demo
 * @author huang
 * @date 2019/2/20
 */
public class VolatileTest {
    volatile  boolean isExit;
    public void tryExit(){
        if (isExit==!isExit){
            //退出线程
            System.exit(0);
        }
    }
    public void setExit(){
        isExit=!isExit;
    }

    public static void main(String[] args) throws InterruptedException {
        final VolatileTest volatileTest=new VolatileTest();
        Thread task1 = new Thread() {
            @Override
            public void run() {
                System.out.println("task1 start");
                while (true) {
                    volatileTest.tryExit();
                }
            }
        };

        task1.start();
        Thread task2 = new Thread() {
            @Override
            public void run() {
                System.out.println("task2 start");
                while (true){
                    volatileTest.setExit();
                }
            }
        };
        task2.start();
        Thread.sleep(10000);
    }
}
